// pages/serve/exam/exam.js
var second = 2700 //45分钟
// var newIndex = 0
var app = getApp()
var setTime;
var mistakesArr = []//错题
var correct = 0
//触屏开始点坐标
var startDot = {
  X: 0,
  Y: 0
};
//触屏到点坐标
var touchDot = {
  X: 0,
  Y: 0
};
var time2 = 0;  //触屏时间
var number2;     //定时器ID
var newIndex = 0//设置活动菜单的index
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */

  data: {
    bar_Height: wx.getSystemInfoSync().statusBarHeight + 45,
    chapterName: "章节练习",
    title: "1",
    chapterClickTops: true,
    topicArr: [],
    gif: "true",

    topicObj: {},
    topicArrInd: 0,//正在做的题的数组下标
    topicYes: 0,//正确
    topicNo: 0,//错误
    view1: 'selection1',
    view2: 'selection1',
    view3: 'selection1',
    view4: 'selection1',
    falseOption: ['', '', '', ''],
    tureOption: ['', '', '', ''],
    options: ["A", "B", "C", "D"],
    timeMin:'45',
    timeS:'00',
    

  },

  /*选择(单选) */
  viewClick: function (e) {
    var that = this
    var select = e.currentTarget.dataset.id
    var indexs = e.currentTarget.dataset.index
    var c_id = e.currentTarget.dataset.cid
    // 选项没被选择时将执行 
    if (that.data.topicArr[indexs].result == '') {
      // 将选项设置为“已被选择” 
      var arr = that.data.topicArr
      let newObj = arr[indexs]
      // newObj.result = select
      // arr.splice(indexs, 1, newObj)

      let obj = that.data.topicObj
      obj.result = select
      let topicYes = that.data.topicYes
      let topicNo = that.data.topicNo

      if (select == newObj.item_true) {
        obj.yesORno = 1

        topicYes++
      } else {
        obj.yesORno = 2

        topicNo++
        mistakesArr.push(c_id)
      }
      arr.splice(indexs, 1, obj)
      that.setData({
        topicObj: obj,
        topicArr: arr,
        topicYes: topicYes,
        topicNo: topicNo,
      })
    }
    // console.log(that.data.arrTitle)
  },
  /*选择(多选) */
  viewClick2(e) {
    var that = this
    let topicObj = that.data.topicObj
    if (e.currentTarget.dataset.topic == 'A'){
      if (topicObj.topics[0] == ""){
        topicObj.topics[0] = {
          name: e.currentTarget.dataset.topic,
          content: e.currentTarget.dataset.id
        }
      }else{
        topicObj.topics[0] = ''
      }
    }
    if (e.currentTarget.dataset.topic == 'B') {
      if (topicObj.topics[1] == "") {
        topicObj.topics[1] = {
          name: e.currentTarget.dataset.topic,
          content: e.currentTarget.dataset.id
        }
      } else {
        topicObj.topics[1] = ''
      }
    }
    if (e.currentTarget.dataset.topic == 'C') {
      if (topicObj.topics[2] == "") {
        topicObj.topics[2] = {
          name: e.currentTarget.dataset.topic,
          content: e.currentTarget.dataset.id
        }
      } else {
        topicObj.topics[2] = ''
      }
    }
    if (e.currentTarget.dataset.topic == 'D') {
      if (topicObj.topics[3] == "") {
        topicObj.topics[3] = {
          name: e.currentTarget.dataset.topic,
          content: e.currentTarget.dataset.id
        }
      } else {
        topicObj.topics[3] = ''
      }
    }
    that.setData({
      topicObj: topicObj
    })

  },
  /**多选确定 */
  buttonYes(e){
    var that = this
    let topicObj = that.data.topicObj
    let words = topicObj.item_true
    let newKeyArr = []
    let result_ture = []
    let c_id = e.currentTarget.dataset.cid
    // console.log(topicObj.topics)
    let nua = 0
    for (let p = 0; p < topicObj.topics.length;p++){
      if (topicObj.topics[p] != ''){
        nua++
      }
    }
    if (nua < 2){
      wx.showToast({
        title:"至少选择两项",
        icon:'none',
        duration:1000
      })
    }else{
      topicObj.result = topicObj.topics
      // console.log(topicObj)
      var indexs = e.currentTarget.dataset.index
      for (let j = 0; words.indexOf("|") + 1 > 0; j++) {
        let newKey = words.slice(0, words.indexOf("|"))
        words = words.slice(words.indexOf("|") + 1)
        newKeyArr.push(newKey)
        if (words.indexOf("|") < 0) {
          newKeyArr.push(words)
        }
      }
      // 
      for (let g = 0; g < topicObj.option.length; g++) {
        let optionTrue = false
        let optionContent = ''
        for (let f = 0; f < newKeyArr.length; f++) {
          if (topicObj.option[g] == newKeyArr[f]) {
            optionTrue = true
            optionContent = newKeyArr[f]
          }
        }
        if (optionTrue) {
          result_ture.push(optionContent)
        } else {
          result_ture.push('')
        }
      }
      // console.log(result_ture, "result_ture")
      topicObj.result_ture = result_ture
      let num = 0
      for (let x = 0; x < newKeyArr.length; x++) {
        for (let y = 0; y < topicObj.topics.length; y++) {
          if (newKeyArr[x] == topicObj.topics[y].content) {
            num++
          }
        }
      }
      let topicYes = that.data.topicYes
      let topicNo = that.data.topicNo
      if (num == newKeyArr.length) {
        topicObj.yesORno = 1
        topicYes++
      } else {
        topicObj.yesORno = 2

        topicNo++
        mistakesArr.push(c_id)
      }
      var arr = that.data.topicArr
      arr.splice(indexs, 1, topicObj)
      that.setData({
        topicObj: topicObj,
        topicYes: topicYes,
        topicNo: topicNo,
        topicArr: arr,

      })
    }

  },
  // /**
  //    * 触屏开始计时和获取坐标
  //    */
  // touchStarts: function (event) {
  //   // console.log("dasdas")
  //   startDot.X = event.touches[0].pageX;
  //   startDot.Y = event.touches[0].pageY;
  //   // console.log(startDot.X, startDot.Y)
  //   // number2 = setInterval(function () {
  //   //   time2++;
  //   // }, 100);
  // },
  // /**
  //  * 判断滑动距离和时间是否需要切换页面
  //  */
  // touchMoves: function (event) {
  //   var that = this
  //   touchDot.X = event.touches[0].pageX;
  //   touchDot.Y = event.touches[0].pageY;
  //   let arrs = that.data.topicArr
  //   //向左滑处理
  //   if ((startDot.X - touchDot.X) > 100 && (startDot.Y - touchDot.Y) < 150 && time2 == 0) {

  //     if (newIndex < arrs.length - 1) {
  //       // console.log("下一页")
  //       time2 = 2;
  //       newIndex = newIndex + 1
  //       let topicObj = arrs[newIndex]
  //       let topicObjContent = topicObj.content//获取题目
  //       let topicObjKey = topicObj.key_words//获取关键字
  //       let falseKey = topicObj.key_false//获取关键字
  //       let tureKey = topicObj.key_true//获取关键字
  //       if (topicObjKey) {
  //         keyWords(that, topicObjContent, topicObjKey)
  //       } else {
  //         that.setData({
  //           arrTitle: [],
  //         })
  //       }
  //       if (falseKey != '') {
  //         falseKeys(that, falseKey, topicObj.option)
  //       } else {
  //         that.setData({
  //           falseOption: ['', '', '', '']
  //         })
  //       }
  //       if (tureKey != '') {
  //         tureKeys(that, tureKey, topicObj.option)
  //       } else {
  //         that.setData({
  //           tureOption: ['', '', '', '']
  //         })
  //       }
  //       if (arrs[newIndex].culture == 1) {
  //         arrs[newIndex].topics = ['', '', '', '']
  //       }
  //       // console.log(arrs[newIndex])
  //       that.setData({
  //         topicArr: arrs,
  //         topicObj: arrs[newIndex],
  //         view1: 'selection1',
  //         view2: 'selection1',
  //         view3: 'selection1',
  //         view4: 'selection1',
  //         topicArrInd: newIndex,
        
  //       })
  //     } else {
  //       wx.showToast({
  //         title: "这已经是最后一题了",
  //         icon: 'none',
  //         duration: 1000
  //       })
  //     }
    
  //   }
  //   //向右滑处理
  //   if ((touchDot.X - startDot.X) > 100 && (touchDot.Y - startDot.Y) < 150 && time2 == 0) {
  //     if (newIndex > 0) {
  //       // console.log("上一页")
  //       newIndex = newIndex - 1
  //       time2 = 1;

  //       let topicObj = arrs[newIndex]
  //       let topicObjContent = topicObj.content//获取题目
  //       let topicObjKey = topicObj.key_words//获取关键字
  //       let falseKey = topicObj.key_false//获取关键字
  //       let tureKey = topicObj.key_true//获取关键字
  //       if (topicObjKey) {
  //         keyWords(that, topicObjContent, topicObjKey)
  //       } else {
  //         that.setData({
  //           arrTitle: [],
  //         })
  //       }

  //       if (falseKey != '') {
  //         falseKeys(that, falseKey, topicObj.option)
  //       } else {
  //         that.setData({
  //           falseOption: ['', '', '', '']
  //         })
  //       }
  //       if (tureKey != '') {
  //         tureKeys(that, tureKey, topicObj.option)
  //       } else {
  //         that.setData({
  //           tureOption: ['', '', '', '']

  //         })
  //       }
  //       if (arrs[newIndex].culture == 1) {
  //         arrs[newIndex].topics = ['', '', '', '']
  //       }
  //       // console.log(arrs[newIndex])
  //       that.setData({
  //         topicArr: arrs,
  //         topicObj: arrs[newIndex],
  //         view1: 'selection1',
  //         view2: 'selection1',
  //         view3: 'selection1',
  //         view4: 'selection1',
  //         topicArrInd: newIndex,
  //       })
  //     } else {
  //       wx.showToast({
  //         title: "这已经是第一题了",
  //         icon: 'none',
  //         duration: 1000
  //       })
  //     }
  //     // clearInterval(number2);
  //     // time2 = 0;
  //   }
  // },
  // /**
  //  * 结束触屏重置计时
  //  */
  // touchEnds: function (event) {
  //   // clearInterval(number2);
  //   time2 = 0;
  //   this.setData({
  //     view1: 'selection1',
  //     view2: 'selection1',
  //     view3: 'selection1',
  //     view4: 'selection1',
  //   })
  // },
  //上一页
  previous(e){
    var that = this
    let arrs = that.data.topicArr
    if (newIndex > 0) {
        // console.log("上一页")
        newIndex = newIndex - 1
        time2 = 1;

        let topicObj = arrs[newIndex]
        let topicObjContent = topicObj.content//获取题目
        let topicObjKey = topicObj.key_words//获取关键字
        let falseKey = topicObj.key_false//获取关键字
        let tureKey = topicObj.key_true//获取关键字
        if (topicObjKey) {
          keyWords(that, topicObjContent, topicObjKey)
        } else {
          that.setData({
            arrTitle: [],
          })
        }

        if (falseKey != '') {
          falseKeys(that, falseKey, topicObj.option)
        } else {
          that.setData({
            falseOption: ['', '', '', '']
          })
        }
        if (tureKey != '') {
          tureKeys(that, tureKey, topicObj.option)
        } else {
          that.setData({
            tureOption: ['', '', '', '']

          })
        }
        if (arrs[newIndex].culture == 1) {
          arrs[newIndex].topics = ['', '', '', '']
        }
        // console.log(arrs[newIndex])
        that.setData({
          topicArr: arrs,
          topicObj: arrs[newIndex],
          view1: 'selection1',
          view2: 'selection1',
          view3: 'selection1',
          view4: 'selection1',
          topicArrInd: newIndex,
        })
    } else {
      wx.showToast({
        title: "这已经是第一题了",
        icon: 'none',
        duration: 1000
      })
    }
  },
  //下一页
  next(e) {
    var that = this
    let arrs = that.data.topicArr
    // console.log(that.data.topicArr)
    // console.log(newIndex)


    if (newIndex < arrs.length - 1) {
        // console.log("下一页")
        time2 = 2;
        newIndex = newIndex + 1
        let topicObj = arrs[newIndex]
        let topicObjContent = topicObj.content//获取题目
        let topicObjKey = topicObj.key_words//获取关键字
        let falseKey = topicObj.key_false//获取关键字
        let tureKey = topicObj.key_true//获取关键字
        if (topicObjKey) {
          keyWords(that, topicObjContent, topicObjKey)
        } else {
          that.setData({
            arrTitle: [],
          })
        }
        if (falseKey != '') {
          falseKeys(that, falseKey, topicObj.option)
        } else {
          that.setData({
            falseOption: ['', '', '', '']
          })
        }
        if (tureKey != '') {
          tureKeys(that, tureKey, topicObj.option)
        } else {
          that.setData({
            tureOption: ['', '', '', '']
          })
        }
        if (arrs[newIndex].culture == 1) {
          arrs[newIndex].topics = ['', '', '', '']
        }
        // console.log(arrs[newIndex])
        that.setData({
          topicArr: arrs,
          topicObj: arrs[newIndex],
          view1: 'selection1',
          view2: 'selection1',
          view3: 'selection1',
          view4: 'selection1',
          topicArrInd: newIndex,

        })
    } else {
      wx.showToast({
        title: "这已经是最后一题了",
        icon: 'none',
        duration: 1000
      })
    }

  },



  //题号查看
  chapterClickTop(e) {
    var that = this
    var chapterClickTops = that.data.chapterClickTops
    let widthBL = 750 / wx.getSystemInfoSync().windowWidth
    let heightWin = wx.getSystemInfoSync().windowHeight / 2 - (80 / widthBL)
    var animation2 = wx.createAnimation({});
    if (chapterClickTops) {

      animation2.translate(0, -heightWin).step({ duration: 500 })
      that.setData({
        chapterClickTops: false,
        animationData: animation2.export()
      })
    } else {
      animation2.translate(0, 0).step({ duration: 500 })
      that.setData({
        chapterClickTops: true,
        animationData: animation2.export()
      })
    }

  },

  //题目跳转
  topicClick(e) {
    var that= this
    // console.log(e.currentTarget.dataset.index)
    newIndex = e.currentTarget.dataset.index

    var animation2 = wx.createAnimation({});
    animation2.translate(0, 0).step({ duration: 500 })
    let arrs = that.data.topicArr
    let topicObj = arrs[newIndex]
    let topicObjContent = topicObj.content//获取题目
    let topicObjKey = topicObj.key_words//获取关键字
    let falseKey = topicObj.key_false//获取关键字
    let tureKey = topicObj.key_true//获取关键字
    if (topicObjKey) {
      keyWords(that, topicObjContent, topicObjKey)
    } else {
      that.setData({
        arrTitle: [],
      })
    }

    if (falseKey != '') {
      falseKeys(that, falseKey, topicObj.option)
    } else {
      that.setData({
        falseOption: ['', '', '', '']
      })
    }
    if (tureKey != '') {
      tureKeys(that, tureKey, topicObj.option)
    } else {
      that.setData({
        tureOption: ['', '', '', '']
      })
    }
    if (arrs[e.currentTarget.dataset.index].culture == 1) {
      arrs[e.currentTarget.dataset.index].topics = ['','','','']
    }
    that.setData({
      topicArr: arrs,
      topicObj: arrs[e.currentTarget.dataset.index],
      topicArrInd: e.currentTarget.dataset.index,
      chapterClickTops: true,
      animationData: animation2.export()
    })
  },
  //交卷
  submitExam(e){
    var that = this
    // if (that.data.topicYes + that.data.topicNo < 100){
      let con = ''
    if (app.titleStudy == 1){
      con = '你本次考试正确' + that.data.topicYes + '，错误' + that.data.topicNo + '考试成绩为' + that.data.topicYes +'是否确定交卷？'
    }
    if (app.titleStudy == 4) {
      con = '你本次考试正确' + that.data.topicYes + '，错误' + that.data.topicNo + '考试成绩为' + that.data.topicYes * 2 + '是否确定交卷？'
    }
      wx.showModal({
        title: '你的成绩',
        content: con,
        success: function (res) {
          if (res.confirm) {
            clearInterval(setTime)
            // console.log(second, mistakesArr)
            let record = 0
            if (app.titleStudy == 1) {
              record = that.data.topicYes
            }
            if (app.titleStudy == 4) {
              record = that.data.topicYes * 2
            }
            submits(record, 2700 - second, that)
            
          } 
        }
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    let widthBL = 750 / wx.getSystemInfoSync().windowWidth
    newIndex = 0
    mistakesArr = []
    second = 2700
    let topicObj = that.data.topicArr[0]
    // console.log(topicObj)
   
    that.setData({
      heights: wx.getSystemInfoSync().windowHeight / 2,
      heightx: 80 / widthBL,
      heightd: wx.getSystemInfoSync().windowHeight / 2 - (80 / widthBL),
      
    })
    topicSuccessively(app.titleStudy, app.cardType, that)

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideShareMenu()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(setTime)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
//获取题
function topicSuccessively(course, car_status, that) {
  wx.request({
    url: 'https://minitest.17jxyx.com/api/v1/test/exam',
    method: "POST",
    header: {
      token: app.token
    },
    data: {
      course: course,
      car_status: car_status
    },
    success: function (res) {
      // console.log(res)
      let topicObj = res.data[0]
      let topicObjContent = topicObj.content//获取题目
      let topicObjKey = topicObj.key_words//获取关键字
      let falseKey = topicObj.key_false//获取关键字
      let tureKey = topicObj.key_true//获取关键字

      if (topicObjKey){
        keyWords(that, topicObjContent, topicObjKey)
      }else{
        that.setData({
          arrTitle: [],
        })
      }

      if (falseKey !='') {
        falseKeys(that, falseKey, res.data[0].option)
      } else {
        that.setData({
          falseTitle: [],
        })
      }
      if (tureKey != '') {
        tureKeys(that, tureKey, res.data[0].option)
      } else {
        that.setData({
          tureTitle: [],
        })
      }
      let arrs = res.data
      if (arrs[0].culture == 1){
        arrs[0].topics = ['', '', '', '']
      }
      setTime = setInterval(function () {
        second--;
        let timeMin = parseInt(second / 60)
        let timeS = Math.ceil(second % 60)
        if (timeMin < 10) {
          timeMin = "0" + timeMin
        }
        if (timeS < 10) {
          timeS = "0" + timeS
        }
        if (second <= 0) {
          clearInterval(setTime)
          let record = 0
          if (app.titleStudy == 1) {
            record = that.data.topicYes
          }
          if (app.titleStudy == 4) {
            record = that.data.topicYes * 2
          }
          submits(record, 0, that)
          timeS = "00"
          timeMin = "00"
        }
        that.setData({
          timeS: timeS,
          timeMin: timeMin
        });

      }, 1000)
      that.setData({
        topicArr: arrs,
        topicObj: res.data[0],
        gif: "false",

      })
    },
    fail: function (res) {
      console.log(res)
    }
  })
}
//关键字
function keyWords(that,texts,wordss){
  let words = wordss;
  let contents = texts;
  let arrTitle = []
  // console.log(words)
  // console.log(words, words.indexOf(","))
  let newKeyArr = []
  if (words.indexOf(",") > 0) {
    for (let j = 0; words.indexOf(",") + 1 > 0; j++) {
      let newKey = words.slice(0, words.indexOf(","))
      words = words.slice(words.indexOf(",") + 1)
      newKeyArr.push(newKey)
      if (words.indexOf(",") < 0) {
        newKeyArr.push(words)
      }
    }
  } else {
    newKeyArr.push(words)
  }

  // console.log(newKeyArr)
  for (let i = 0; i < newKeyArr.length; i++) {
    let obj1 = {
      content: contents.substring(0, contents.indexOf(newKeyArr[i])),
      font: 1
    }
    arrTitle.push(obj1)
    let obj2 = {
      content: newKeyArr[i],
      font: 2
    }
    arrTitle.push(obj2)
    if (i + 1 == newKeyArr.length) {
      let obj3 = {
        content: contents.substring(contents.indexOf(newKeyArr[i]) + newKeyArr[i].length),
        font: 1
      }
      arrTitle.push(obj3)
    }
    contents = contents.substring(contents.indexOf(newKeyArr[i]) + newKeyArr[i].length)
  }
  that.setData({
    arrTitle: arrTitle,
  })
}

//错误提示
function falseKeys(that, wordss, arrOption){
  // console.log(wordss, arrOption)
  let words = wordss;
  let falseOption = ['', '', '', '']
  let newKeyArr = []
  if (words.indexOf(",") > 0) {
    for (let j = 0; words.indexOf(",") + 1 > 0; j++) {
      let newKey = words.slice(0, words.indexOf(","))
      words = words.slice(words.indexOf(",") + 1)
      newKeyArr.push(newKey)
      if (words.indexOf(",") < 0) {
        newKeyArr.push(words)
      }
    }
  } else {
    newKeyArr.push(words)
  }
  for (let k = 0; k < arrOption.length;k++){
    let newArrs = []
    let contents = arrOption[k]
    for (let i = 0; i < newKeyArr.length; i++) {
      if (contents.indexOf(newKeyArr[i]) < 0){
      }else{
        let obj1 = {
          content: contents.substring(0, contents.indexOf(newKeyArr[i])),
          font: 1
        }
        newArrs.push(obj1)
        let obj2 = {
          content: newKeyArr[i],
          font: 2
        }
        newArrs.push(obj2)
        contents = contents.substring(contents.indexOf(newKeyArr[i]) + newKeyArr[i].length)

      }
      if (i+1 == newKeyArr.length) {
        let obj3 = {
          content: contents,
          font: 1
        }
        newArrs.push(obj3)
      }
    }
    falseOption[k] = newArrs
  }

  that.setData({
    falseOption:falseOption
    
  })
}
//正确提示
function tureKeys(that, wordss, arrOption) {
  let words = wordss;
  let tureOption = ['', '', '', '']
  let newKeyArr = []
  if (words.indexOf(",") > 0) {
    for (let j = 0; words.indexOf(",") + 1 > 0; j++) {
      let newKey = words.slice(0, words.indexOf(","))
      words = words.slice(words.indexOf(",") + 1)
      newKeyArr.push(newKey)
      if (words.indexOf(",") < 0) {
        newKeyArr.push(words)
      }
    }
  } else {
    newKeyArr.push(words)
  }
  for (let k = 0; k < arrOption.length; k++) {
    let newArrs = []
    let contents = arrOption[k]
    for (let i = 0; i < newKeyArr.length; i++) {
      if (contents.indexOf(newKeyArr[i]) < 0) {
      } else {
        let obj1 = {
          content: contents.substring(0, contents.indexOf(newKeyArr[i])),
          font: 1
        }
        newArrs.push(obj1)
        let obj2 = {
          content: newKeyArr[i],
          font: 2
        }
        newArrs.push(obj2)
        contents = contents.substring(contents.indexOf(newKeyArr[i]) + newKeyArr[i].length)
      }
      if (i + 1 == newKeyArr.length) {
        let obj3 = {
          content: contents,
          font: 1
        }
        newArrs.push(obj3)
      }
    }
    tureOption[k] = newArrs
  
  }
  // console.log(tureOption,"tureOption")
  that.setData({
    tureOption: tureOption
  })
}
//交卷请求
function submits(record, time,that){
  wx.request({
    url: 'https://minitest.17jxyx.com/api/v1/test/log',
    method: "POST",
    data: {
      course: app.titleStudy,//科目
      car_status: app.cardType,//车型
      record: record,//成绩
      time: time,//时间
      error: mistakesArr,//错题
    },
    header: {
      token: app.token
    },
    success: function (res) {
      // console.log(res)
      // console.log(time, that.data.topicYes, that.data.topicNo)
      wx.navigateTo({
        url: '/pages/serve/transcript/transcript?time=' + time + '&yes=' + that.data.topicYes + '&no=' + that.data.topicNo,
      })
    },
    fail: function (res) {
    }
  })
}